import {ecs} from "db://oops-framework/libs/ecs/ECS";
import {ReconnectComp} from "db://assets/script/game/initialize/comp/reconnectComp";
import {Server} from "db://assets/script/network/ws/server";
import {oops} from "db://oops-framework/core/Oops";
import {openDialogNotify, UIID} from "db://assets/script/game/common/config/gameUiConfig";
import {smc} from "db://assets/script/game/common/singletonModuleComp";
import {maxReconnectAttempts} from "db://assets/script/game/constants/common";

export class ReconnectSystem extends ecs.ComblockSystem implements ecs.IEntityEnterSystem {
    filter(): ecs.IMatcher {
        return ecs.allOf(ReconnectComp)
    }

    entityEnter(entity: ecs.Entity): void {
        // 初始化完成后，删除
        entity.remove(ReconnectComp)
        Server.listen("disconnect", () => {
            // 连接服务器失败，加载载入中
            oops.gui.open(UIID.netinstable)
        })
        // Server.listen("reconnect", () => {
        //     // 重连成功，开始重新登录
        //     oops.gui.remove(UIID.netinstable)
        // })
        Server.listen("close", () => {
            console.error("network lose, reconnect times", Server.s.reconnectAttempts)
            // 需要重新登录
            smc.initialize.reconnect = true
            if (Server.s.reconnectAttempts >= maxReconnectAttempts) {
                // 最后一次也没连上
                console.error("last attempt to connect")
                const tryLogin = () => {
                    // 重新登录
                    if (oops.gui.has(UIID.login)) {
                        oops.gui.remove(UIID.login)
                    }
                    // 移除 loading
                    oops.gui.remove(UIID.netinstable)
                    oops.gui.open(UIID.login)
                }
                openDialogNotify("连接失败", "网络连接失败, 请稍后重试", tryLogin)
            }
        })
    }
}